using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Framework.Core.Io;

namespace Framework.Core.Process.Tasks
{
    internal struct TaskList : ICommand, IProcessTask<IEnumerable<IProcess>>
    {
        public string Name { get { return TaskListName; } }
        public string FileName { get { return TaskListPath; } }
        public string Arguments { get { return string.Empty; } }
        public bool IsNative { get { return false; } }

        private const string TaskListPath = @"PsArgs.exe";
        private static readonly string TaskListName = Path.GetFileNameWithoutExtension(TaskListPath);

        static TaskList()
        {
            TaskListPath.Deploy();
        }

        public IEnumerable<IProcess> Execute(IProcessRunner processRunner)
        {
            return processRunner.Start(this).StandardOutput
                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                .Skip(1)
                .Select(ParseToProcess);
        }

        private static IProcess ParseToProcess(string arg)
        {
            var processInfos = arg.Split('\t');

            var name = processInfos[0];
            var serviceName = processInfos[1];
            var processId = int.Parse(processInfos[2]);
            var path = processInfos[4];
            var args = processInfos[5];

            if (string.IsNullOrWhiteSpace(serviceName))
            {
                return new Process(processId, name, path, args, false);
            }

            return new WindowsService(processId, serviceName, path, args);
        }
    }
}